<?php
/**
 * 苹果推送服务
 * 
 */
class Apns
{
    /**
     * 开发模式
     *
     * @var int
     */
    const MODE_DEV = 0;

    /**
     * 生产模式
     * @var int
     */
    const MODE_PRODUCT = 1;

    protected $_config = array
    (
        self::MODE_DEV => array( 'host' => 'gateway.sandbox.push.apple.com' , 'port' => 2195 ) ,
        self::MODE_PRODUCT => array( 'host' => 'gateway.sandbox.push.apple.com' , 'port' => 2195 ) ,
    );

    /**
     * 当前模式
     *
     * @var int
     */
    protected $_currentMode = self::MODE_DEV;

    /**
    * 单例对象
    */
    public static $singletonObject = null;

    /**
    * 获取单例
    * @param $uId 用户ID
    * @return Apns
    */
    public static function getInstance()
    {
        if( self::$singletonObject == null )
        {
            self::$singletonObject = new self();
        }

        return self::$singletonObject;
    }

    protected function __construct()
    {
        $apnsConfig = & Common::getConfig( 'ApnsConfig' );
        $this->_currentMode = $apnsConfig['mode'];
        $this->_cert = $apnsConfig['cert'];
    }

    /**
     * 向指定设备推送信息
     *
     * @param string $deviceToken //64位字符串
     * @param string $alert //通知内容
     * @param int $badge //通知数字
     * @param string $sound //通知声音
     */
    public function send( $deviceToken ,  $payload )
    {
        $payload = json_encode( $payload );
        $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace( ' ', '', $deviceToken ) ) . chr(0) . chr( strlen( $payload ) ) . $payload;
        $streamContext = stream_context_create();
        stream_context_set_option( $streamContext , 'ssl' , 'local_cert' , $this->_cert );
        $apns = stream_socket_client( 'ssl://' . $this->_config[$this->_currentMode]['host'] . ':' . $this->_config[$this->_currentMode]['port'] , $error , $errorString , 2 , STREAM_CLIENT_CONNECT , $streamContext );
        fwrite( $apns , $apnsMessage );
        fclose( $apns );
    }
}